import { Service } from 'egg';
import { v4 } from 'uuid';
import { ContractsEditRemarkIn } from '../dto/in/contactsIn';
import CommonUtil from '../src/decorator/commonUtil';
import IDBModel from '../src/interface/DBModel';

export default class Contacts extends Service {


    public async request() {
        // await this.app.mysql.beginTransactionScope(async (conn) => {
        //     return { success: true };
        // }, this.ctx);
    }

    /**修改备注 */
    public async editRemark(params: ContractsEditRemarkIn) {
        let find = await this.isFirend(params.memberId);
        if (!find) {
            throw new Error("不是好友");
        }
        else {
            let objs = CommonUtil.pick(find, ["id", "remark"]);
            await this.app.mysql.update(IDBModel.tables.tb_contact, CommonUtil.object2UnderLine({ ...objs, remark: params.remark }));
        }
    }

    /**是否好友 */
    public async isFirend(memberId: string) {
        let ownMemberId = this.service.member.getMemberIdByToken();
        return await this.service.mysql.firstOrDefault<IDBModel.Contact>(IDBModel.tables.tb_contact, {
            where: { otherMemberId: memberId, memberId: ownMemberId, status: [0, 2, 4] }
        })
    }


    /**获取好友列表 */
    public async getContactsList() {
        let memberId = this.service.member.getMemberIdByToken();
        let list = await this.app.mysql.query(`
            SELECT
                tc.id,
                tc.channel,
                tc.other_member_id AS member_id,
                tc.relation_id,
                tc.remark,
                tm.nickname,
                tm.gender,
                tm.avatar,
                tm.signature,
                tm.cover,
                tm.title 
            FROM
                tb_contact tc
                LEFT JOIN tb_member tm ON tm.id = tc.other_member_id 
            WHERE
                member_id = ?
                AND \`status\` IN ( 0, 2, 4 );
            `, [memberId])
        return (list as any[]).map((p) => CommonUtil.filterUnderLine(p));
    }

    /**添加朋友 */
    public async makeFirends(memberId: string, otherMemberId: string, conn?: EggMySQLTransation) {
        const relationId = v4();
        await this.service.mysql.insert<IDBModel.Contact>(IDBModel.tables.tb_contact, {
            relationId,
            channel: 0,
            memberId,
            otherMemberId,
            status: 0
        }, conn);
        await this.service.mysql.insert<IDBModel.Contact>(IDBModel.tables.tb_contact, {
            relationId,
            channel: 0,
            memberId: otherMemberId,
            otherMemberId: memberId,
            status: 0
        }, conn);
    }
}